﻿/*
Configuration Server
 
Provides a single configuration point for the several instances (development, 
staging, testing, production, etc.) for web sites
 
Includes ideas and code from all over the internet. Specially, stacktrace, msdn, github.
 
Copyright (C) 2014 by Jaime Espinosa <jaimeespinosa60@gmail.com>
 
The MIT License (MIT)

Copyright (c) 2014 jaime espinosa

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

  @author Jaime Espinosa <jaimeespinosa60@gmail.com>
  @package configuracion
  @version 0.1
*/

using Configuracion.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.Web.Mvc;

namespace Configuracion.Controllers
{
    public class keyController : baseController
    {
        [Authorize]
        public ActionResult list(int bundleID = 0, string txtFilter = "")
        {
            ViewBag.Exception = "";
            ViewBag.filter = txtFilter;
            string strUserName = "";
            List<int> bundleIDs = default(List<int>);
            mdlBundle bundle = default(mdlBundle);
            IEnumerable<mdlBundleKey> key = default(IEnumerable<mdlBundleKey>);

            if (User.Identity.IsAuthenticated)
                strUserName = User.Identity.Name;

            bundleIDs = (from p in dbContext.Owners.Where(p => p.users.Any(u => u.userName == strUserName))
                             .SelectMany(p => p.bundles)
                         select p.ID).ToList<int>();

            if (bundleIDs.Contains(bundleID))
            {
                bundle = (from p in dbContext.Bundles.Include(p => p.Keys)
                          where p.ID == bundleID
                          select p).FirstOrDefault<mdlBundle>();

                ViewBag.bundleName = bundle.name;
                ViewBag.bundleID = bundle.ID;

                key = from p in bundle.Keys
                      where p.name.ToLower().Contains(txtFilter.ToLower())
                      select p;
            }

            return View(key);
        }
        [Authorize]
        public JsonResult newKey(int bundleID = 0, string strName = "", string strDescription = "")
        {
            string strError = "";
            string strUserName = "";
            mdlBundle bundle = default(mdlBundle);

            if ((bundleID == 0) || (strName == "") || (strDescription == ""))
            {
                return Json(new { error = "invalid parameters" }, JsonRequestBehavior.AllowGet);
            }

            try
            {
                if (User.Identity.IsAuthenticated)
                    strUserName = User.Identity.Name;

                bundle = (from p in dbContext.Owners.Include(p => p.bundles)
                                .Include(p => p.bundles.Select(b => b.Keys))
                                .Where(p => p.users.Any(u => u.userName == strUserName))
                                .SelectMany(p => p.bundles)
                          where p.ID == bundleID
                          select p).FirstOrDefault<mdlBundle>();

                if (bundle == null)
                    return Json(new { error = "Bundle not found" }, JsonRequestBehavior.AllowGet);

                if (bundle.Keys == null)
                    bundle.Keys = new List<mdlBundleKey>();

                bundle.Keys.Add(new mdlBundleKey(strName, strDescription));

                if (dbContext.GetValidationErrors().Count() > 0)
                {
                    foreach (System.Data.Entity.Validation.DbEntityValidationResult error in dbContext.GetValidationErrors())
                        foreach (System.Data.Entity.Validation.DbValidationError valerror in error.ValidationErrors)
                            strError += valerror.ErrorMessage.ToString() + "<br/>";

                    return Json(new { error = "Please verify:" + strError.ToString() }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    dbContext.SaveChanges();
                    return Json(new { OK = "Key created" }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }
        }
        [Authorize]
        public JsonResult editKey(int bundleID = 0, int keyKey = 0, string strName = "", string strDescription = "")
        {
            string strError = "";
            string strUserName = "";
            List<int> bundleIDs = default(List<int>);
            mdlBundle bundle = default(mdlBundle);

            if ((bundleID == 0) || (keyKey == 0) || (strName == "") || (strDescription == ""))
            {
                return Json(new { error = "invalid parameters" }, JsonRequestBehavior.AllowGet);
            }

            try
            {
                if (User.Identity.IsAuthenticated)
                    strUserName = User.Identity.Name;

                bundleIDs = (from p in dbContext.Owners.Where(p => p.users.Any(u => u.userName == strUserName))
                            .SelectMany(p => p.bundles)
                             select p.ID).ToList<int>();

                if (bundleIDs.Contains(bundleID))
                {
                    bundle = (from p in dbContext.Bundles.Include(p => p.Keys)
                              where p.ID == bundleID
                              select p).FirstOrDefault<mdlBundle>();
                }

                if (bundle == null)
                    return Json(new { error = "Bundle not found" }, JsonRequestBehavior.AllowGet);

                if (bundle.Keys == null)
                    return Json(new { error = "Key not found" }, JsonRequestBehavior.AllowGet);

                mdlBundleKey editKey = (from k in bundle.Keys
                                        where k.ID == keyKey
                                        select k).FirstOrDefault<mdlBundleKey>();

                if (editKey == null)
                    return Json(new { error = "Key not found" }, JsonRequestBehavior.AllowGet);

                // UPDATES KEY
                editKey.name = strName;
                editKey.description = strDescription;

                if (dbContext.GetValidationErrors().Count() > 0)
                {
                    foreach (System.Data.Entity.Validation.DbEntityValidationResult error in dbContext.GetValidationErrors())
                        foreach (System.Data.Entity.Validation.DbValidationError valerror in error.ValidationErrors)
                            strError += valerror.ErrorMessage.ToString() + "<br/>";

                    return Json(new { error = "Please verify:" + strError.ToString() }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    dbContext.SaveChanges();
                    return Json(new { OK = "Key updated" }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }
        }
        [Authorize]
        public JsonResult dropKey(int bundleID = 0, int keyKey = 0)
        {
            string strError = "";
            string strUserName = "";
            List<int> bundleIDs = default(List<int>);
            mdlBundle bundle = default(mdlBundle);

            if ((bundleID == 0) || (keyKey == 0))
            {
                return Json(new { error = "invalid parameters" }, JsonRequestBehavior.AllowGet);
            }

            try
            {
                if (User.Identity.IsAuthenticated)
                    strUserName = User.Identity.Name;

                bundleIDs = (from p in dbContext.Owners.Where(p => p.users.Any(u => u.userName == strUserName))
                            .SelectMany(p => p.bundles)
                             select p.ID).ToList<int>();

                if (bundleIDs.Contains(bundleID))
                {
                    bundle = (from p in dbContext.Bundles.Include(p => p.Keys)
                              where p.ID == bundleID
                              select p).FirstOrDefault<mdlBundle>();
                }

                if (bundle == null)
                    return Json(new { error = "Bundle not found" }, JsonRequestBehavior.AllowGet);

                if (bundle.Keys == null)
                    return Json(new { error = "Key not found" }, JsonRequestBehavior.AllowGet);

                mdlBundleKey removeKey = (from k in bundle.Keys
                                          where k.ID == keyKey
                                          select k).FirstOrDefault<mdlBundleKey>();

                if (removeKey == null)
                    return Json(new { error = "Key not found" }, JsonRequestBehavior.AllowGet);

                // REMOVE THE KEY
                bundle.Keys.Remove(removeKey);

                if (dbContext.GetValidationErrors().Count() > 0)
                {
                    foreach (System.Data.Entity.Validation.DbEntityValidationResult error in dbContext.GetValidationErrors())
                        foreach (System.Data.Entity.Validation.DbValidationError valerror in error.ValidationErrors)
                            strError += valerror.ErrorMessage.ToString() + "<br/>";

                    return Json(new { error = "Please verify:" + strError.ToString() }, JsonRequestBehavior.AllowGet);
                }
                else
                {
                    dbContext.SaveChanges();
                    return Json(new { OK = "Key removed" }, JsonRequestBehavior.AllowGet);
                }
            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }
        }
        [Authorize]
        public JsonResult infoKey(int bundleID = 0, int keyKey = 0)
        {
            string strUserName = "";
            List<int> bundleIDs = default(List<int>);
            mdlBundle bundle = default(mdlBundle);

            mdlBundleKey returnKey = default(mdlBundleKey);

            if ((bundleID == 0) || (keyKey == 0))
            {
                return Json(new { error = "invalid parameters" }, JsonRequestBehavior.AllowGet);
            }

            try
            {
                if (User.Identity.IsAuthenticated)
                    strUserName = User.Identity.Name;

                bundleIDs = (from p in dbContext.Owners.Where(p => p.users.Any(u => u.userName == strUserName))
                            .SelectMany(p => p.bundles)
                             select p.ID).ToList<int>();

                if (bundleIDs.Contains(bundleID))
                {
                    bundle = (from p in dbContext.Bundles.Include(p => p.Keys)
                              where p.ID == bundleID
                              select p).FirstOrDefault<mdlBundle>();
                }

                if (bundle == null)
                    return Json(new { error = "Bundle not found" }, JsonRequestBehavior.AllowGet);

                if (bundle.Keys == null)
                    return Json(new { error = "Key not found" }, JsonRequestBehavior.AllowGet);

                returnKey = (from k in bundle.Keys
                             where k.ID == keyKey
                             select k).FirstOrDefault<mdlBundleKey>();

                if (returnKey == null)
                    return Json(new { error = "Key not found" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }

            return Json(new { OK = "Key obtained", data = returnKey }, JsonRequestBehavior.AllowGet);
        }
        [Authorize]
        public JsonResult keyList(int bundleID = 0)
        {
            string strUserName = "";
            mdlBundle bundle = default(mdlBundle);

            if (bundleID == 0)
            {
                return Json(new { error = "invalid parameters" }, JsonRequestBehavior.AllowGet);
            }

            try
            {
                List<int> bundleIDs = default(List<int>);

                if (User.Identity.IsAuthenticated)
                    strUserName = User.Identity.Name;

                bundleIDs = (from p in dbContext.Owners.Where(p => p.users.Any(u => u.userName == strUserName))
                                 .SelectMany(p => p.bundles)
                             select p.ID).ToList<int>();

                if (bundleIDs.Contains(bundleID))
                {
                    bundle = (from p in dbContext.Bundles.Include(p => p.Keys)
                              where p.ID == bundleID
                              select p).FirstOrDefault<mdlBundle>();
                }

                if (bundle == null)
                    return Json(new { error = "Bundle not found" }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                return Json(new { error = infoExcepcion(ex) }, JsonRequestBehavior.AllowGet);
            }

            return Json(new { OK = "List obtained", data = bundle.Keys }, JsonRequestBehavior.AllowGet);
        }
    }
}